/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ressources;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import modele.Database;
import modele.DatabaseManager;
import org.restlet.data.MediaType;
import org.restlet.ext.xml.DomRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.Get;
import org.restlet.resource.ResourceException;
import org.restlet.resource.ServerResource;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 *
 * @author Roman
 */
public class BDRessource extends ServerResource {
    private String dbName;
    private List<String> tables;
    private Representation resultat;

    protected void doInit() throws ResourceException {
        // Get the "itemName" attribute value taken from the URI template  
        // /items/{itemName}.  
        this.dbName = (String) getRequest().getAttributes().get("dbName");

        Database.setConnectionData(dbName, "root", "");
        // Get the item directly from the "persistence layer".  
        this.tables = DatabaseManager.getLstTables();
        setExisting(this.tables != null);
    }

    /** Représentation en réponse à une requête de méthode GET */
    @Get("text/xml")
    public Representation toXML() {
        System.out.println("GET BD");
        try {
            DomRepresentation dom = new DomRepresentation(MediaType.TEXT_XML);
            // Generer un DOM representant la ressource
            Document doc = dom.getDocument();
            Element root = doc.createElement("database");
            root.setAttribute("name", dbName);
            doc.appendChild(root);
            for (String table : tables) {
                Element database = doc.createElement("table");
                root.appendChild(database);
                database.setTextContent(table);
            }
            resultat = dom;
        } catch (IOException ex) {
            Logger.getLogger(BDsRessource.class.getName()).log(Level.SEVERE, null, ex);
        }
        return resultat;
    }
}
